<template>
  <div class="main-container">
    <el-row :gutter="20">
      <el-col :span="5">
        <div class="data-show">
          <div class="data-actions">
            <h3>功能选择</h3>
          </div>
          <!-- 内容区 -->
          <div class="data-table">
            <div class="apps_container">
              <el-radio @change="selectAppChange" v-model="selectApp" v-for="(item, index) in apps" :key="index" :label="item.label" :value="item.value"></el-radio>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="19">
        <transition name="loading" mode="out-in">
          <!-- 公钥解密 -->
          <div class="task-container" v-if="selectApp === 0">
            <el-form ref="oneForm" :model="oneData" :rules="rules">
              <!-- 公钥字段 -->
              <div class="data-show">
                <!-- 标题 -->
                <div class="data-actions data-title-between">
                  <h3>服务器公钥解密</h3> 
                </div>
                <!-- 内容区 -->
                <div class="data-table">
                  <!-- 通用布局行 -->
                  <div class="common-row">
                    <div class="common-item item-5">
                      <label class="condition-label">发布用户</label>
                      <el-form-item class="condition-input" prop="userId">
                        <el-input type="text" v-model="oneData.userId" placeholder="请输入用户" />
                      </el-form-item>
                    </div>
                    <!-- 配置项 - 算法类型 -->
                    <div class="common-item item-5">
                      <label class="condition-label">算法模块</label>
                      <el-form-item class="condition-input" prop="keyType">
                        <el-select v-model="oneData.keyType" clearable placeholder="请选择算法模块">
                          <el-option v-for="(item, index) in keyTypes" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                      </el-form-item>
                    </div>
                  </div>
                  <!-- 通用布局行 -->
                  <div class="common-row">
                    <div class="common-item item-10" :class="{'item-upload': uploadObj.oneKeyTextFilePath.showFileList}">
                      <el-tooltip content="切换上传方式" placement="top">
                        <label class="condition-label condition-label-change" @click="changeUploadType('oneKeyTextFilePath', 'keyTextFilePath', oneData)">公钥密文</label>
                      </el-tooltip>
                      <el-form-item class="condition-input" prop="keyTextFilePath">
                        <el-upload
                          drag
                          class="upload"
                          v-if="uploadObj.oneKeyTextFilePath.isUploadType"
                          :ref="uploadObj.uploadRef('oneKeyTextFilePath')"
                          :action="uploadObj.uploadUrl"
                          :limit="1"
                          :show-file-list="uploadObj.oneKeyTextFilePath.showFileList"
                          :before-upload="uploadObj.beforeUpload('oneKeyTextFilePath', 'keyTextFilePath')"
                          :on-success="uploadObj.onSuccess('oneKeyTextFilePath', 'keyTextFilePath',oneData, oneForm)"
                          :on-progress="uploadObj.onProgress('oneKeyTextFilePath')"
                          :on-error="uploadObj.onError('oneKeyTextFilePath')"
                          :on-remove="uploadObj.onRemove('oneKeyTextFilePath')"
                        >
                          <transition name="upload">
                            <div class="upload-empty" v-if="!oneData.keyTextFilePath">
                              <i class="iconfont icon-icon_update upload-icon"></i>
                              <p class="upload-des">拖拽文件至此或点击上传</p>
                            </div>
                            <div class="upload-content" v-else>
                              <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                              <p class="upload-des">{{ uploadObj.oneKeyTextFilePath.fileName }}</p>
                            </div>
                          </transition>
                        </el-upload>
                        <el-input v-else type="textarea" @input="clearData('keyTextFilePath', oneData)" @change="createBlobTxt($event,'oneKeyTextFilePath','keyTextFilePath', oneData, oneForm)" v-model="uploadObj.oneKeyTextFilePath.text" show-word-limit :rows="5" resize="none" placeholder="请输入文本" />
                      </el-form-item>
                    </div>
                  </div>
                </div>
              </div>
              <transition name="upload">
                <!-- 按钮部分 -->
                <div class="btn-groups" v-if="!oneData.key">
                  <button type="button" class="btn btn-normal" @click="handleCancel">取消</button>
                  <button :disabled="oneData.btnFlag" type="button" class="btn" @click="handleOne">解密</button>
                </div>
                <div class="data-show" v-else>
                  <!-- 标题 -->
                  <div class="data-actions data-title-between">
                    <h3>公钥展示</h3>
                  </div>
                  <div class="data-table data-table-scroll">
                    <p class="text-container">
                      {{ oneData.key }}
                    </p>
                  </div>
                </div>
              </transition>
            </el-form>
          </div>

          <!-- 生成公钥 -->
          <div class="task-container" v-else-if="selectApp === 1">
            <el-form ref="twoForm" :model="twoData" :rules="rules">
              <!-- 公钥字段 -->
              <div class="data-show">
                <!-- 标题 -->
                <div class="data-actions data-title-between">
                  <h3>生成协商密钥参数</h3> 
                </div>
                <!-- 内容区 -->
                <div class="data-table">
                  <!-- 通用布局行 -->
                  <div class="common-row">
                    <div class="common-item item-5">
                      <label class="condition-label">发布用户</label>
                      <el-form-item class="condition-input" prop="userId">
                        <el-input type="text" v-model="twoData.userId" placeholder="请输入用户" />
                      </el-form-item>
                    </div>
                    <!-- 配置项 - 算法类型 -->
                    <div class="common-item item-5">
                      <label class="condition-label">算法模块</label>
                      <el-form-item class="condition-input" prop="keyType">
                        <el-select v-model="twoData.keyType" clearable placeholder="请选择算法模块">
                          <el-option v-for="(item, index) in keyTypes" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                      </el-form-item>
                    </div>
                  </div>
                </div>
              </div>
              <transition name="upload" mode="out-in">
                <!-- 按钮部分 -->
                <div class="btn-groups" v-if="!twoData.keyText">
                  <button type="button" class="btn btn-normal" @click="handleCancel">取消</button>
                  <button :disabled="twoData.btnFlag" type="button" class="btn" @click="handleTwo">生成</button>
                </div>
                <!-- 公钥发布结果部分 -->
                <div class="data-show" v-else>
                  <!-- 标题 -->
                  <div class="data-actions data-title-between">
                    <h3>协商密钥参数</h3>
                    <div class="data-title-actions">
                      <span class="action aniTxtBtn" @click="copyText('keyText', twoData, '密文为空，请稍后重试或联系管理员')">复制</span>
                      <span class="action aniTxtBtn" @click="downText('keyText', twoData, '未提供密文，请稍后重试或联系管理员')">下载</span>
                    </div>
                  </div>
                  <div class="data-table data-table-scroll">
                    <p class="text-container">
                      {{ changeJSON(twoData.keyText) }}
                    </p>
                  </div>
                </div>
              </transition>
            </el-form>
          </div>

          <!-- 共享密钥提取 -->
          <div class="task-container" v-else-if="selectApp === 2">
            <el-form ref="threeForm" :model="threeData" :rules="threeRules">
              <!-- 公钥字段 -->
              <div class="data-show">
                <!-- 标题 -->
                <div class="data-actions data-title-between">
                  <h3>协商密钥生成</h3> 
                </div>
                <!-- 内容区 -->
              <div class="data-table">
                <!-- 通用布局行 -->
                <div class="common-row">
                  <div class="common-item item-5">
                    <label class="condition-label">发布用户</label>
                    <el-form-item class="condition-input" prop="userId">
                      <el-input type="text" v-model="threeData.userId" placeholder="请输入用户" />
                    </el-form-item>
                  </div>
                  <!-- 配置项 - 算法类型 -->
                  <div class="common-item item-5">
                    <label class="condition-label">算法模块</label>
                    <el-form-item class="condition-input" prop="keyType">
                      <el-select v-model="threeData.keyType" clearable placeholder="请选择算法模块">
                        <el-option v-for="(item, index) in keyTypes" :key="index" :label="item.label" :value="item.value"></el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                </div>
                <!-- 通用布局行 -->
                <div class="common-row">
                  <div class="common-item item-10" :class="{'item-upload': uploadObj.threeKeyTextFilePath.showFileList}">
                    <el-tooltip content="切换上传方式" placement="top">
                      <label class="condition-label condition-label-change" @click="changeUploadType('threeKeyTextFilePath', 'keyTextFilePath', threeData)">服务器公钥密文</label>
                    </el-tooltip>
                    <el-form-item class="condition-input" prop="keyTextFilePath">
                      <el-upload
                        drag
                        class="upload"
                        v-if="uploadObj.threeKeyTextFilePath.isUploadType"
                        :ref="uploadObj.uploadRef('threeKeyTextFilePath')"
                        :action="uploadObj.uploadUrl"
                        :limit="1"
                        :show-file-list="uploadObj.threeKeyTextFilePath.showFileList"
                        :before-upload="uploadObj.beforeUpload('threeKeyTextFilePath', 'keyTextFilePath')"
                        :on-success="uploadObj.onSuccess('threeKeyTextFilePath', 'keyTextFilePath',threeData, threeForm)"
                        :on-progress="uploadObj.onProgress('threeKeyTextFilePath')"
                        :on-error="uploadObj.onError('threeKeyTextFilePath')"
                        :on-remove="uploadObj.onRemove('threeKeyTextFilePath')"
                      >
                        <transition name="upload">
                          <div class="upload-empty" v-if="!threeData.keyTextFilePath">
                            <i class="iconfont icon-icon_update upload-icon"></i>
                            <p class="upload-des">拖拽文件至此或点击上传</p>
                          </div>
                          <div class="upload-content" v-else>
                            <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                            <p class="upload-des">{{ uploadObj.threeKeyTextFilePath.fileName }}</p>
                          </div>
                        </transition>
                      </el-upload>
                      <el-input v-else type="textarea" @input="clearData('keyTextFilePath', threeData)" @change="createBlobTxt($event,'threeKeyTextFilePath','keyTextFilePath', threeData, threeForm)" v-model="uploadObj.threeKeyTextFilePath.text" show-word-limit :rows="5" resize="none" placeholder="请输入文本" />
                    </el-form-item>
                  </div>
                </div>
              </div>
              </div>
              
              <transition name="upload">
                <!-- 按钮部分 -->
                <div class="btn-groups" v-if="!threeData.key">
                  <button type="button" class="btn btn-normal" @click="handleCancel">取消</button>
                  <button :disabled="threeData.btnFlag" type="button" class="btn" @click="handleThree">生成</button>
                </div>
                <div class="data-show" v-else>
                  <!-- 标题 -->
                  <div class="data-actions data-title-between">
                    <h3>协商密钥展示</h3>
                    <div class="data-title-actions">
                      <!-- <span class="action aniTxtBtn" @click="downText('key', threeData, '未提供协商密钥，请稍后重试或联系管理员', 'key.txt', 'text/plain')">下载</span> -->
                      <span class="action aniTxtBtn" @click="downText('key', threeData, '未提供协商密钥，请稍后重试或联系管理员', 'key.txt', 'text/plain')">下载</span>
                    </div>
                  </div>
                  <div class="data-table data-table-scroll">
                    <p class="text-container">
                      {{ threeData.key }}
                    </p>
                  </div>
                </div>
              </transition>
            </el-form>
          </div>

          <!-- 生成签名 -->
          <div class="task-container" v-else-if="selectApp === 3">
            <el-form ref="fourForm" :model="fourData" :rules="rules">
              <div class="data-show">
                <!-- 标题 -->
                <div class="data-actions data-title-between">
                  <h3>生成签名</h3> 
                </div>
                <!-- 内容区 -->
                <div class="data-table">
                  <!-- 通用布局行 -->
                  <div class="common-row">
                    <div class="common-item item-5">
                      <label class="condition-label">发布用户</label>
                      <el-form-item class="condition-input" prop="userId">
                        <el-input type="text" v-model="fourData.userId" placeholder="请输入用户" />
                      </el-form-item>
                    </div>
                    <!-- 配置项 - 算法类型 -->
                    <div class="common-item item-5">
                      <label class="condition-label">算法模块</label>
                      <el-form-item class="condition-input" prop="keyType">
                        <el-select v-model="fourData.keyType" clearable placeholder="请选择算法模块">
                          <el-option v-for="(item, index) in keyTypes" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                      </el-form-item>
                    </div>
                  </div>
                </div>
              </div>
              <transition name="upload" mode="out-in">
                <!-- 按钮部分 -->
                <div class="btn-groups" v-if="!fourData.keyText">
                  <button type="button" class="btn btn-normal" @click="handleCancel">取消</button>
                  <button :disabled="fourData.btnFlag" type="button" class="btn" @click="handleFour">生成</button>
                </div>
                <!-- 公钥发布结果部分 -->
                <div class="data-show" v-else>
                  <!-- 标题 -->
                  <div class="data-actions data-title-between">
                    <h3>签名文件</h3>
                    <div class="data-title-actions">
                      <span class="action aniTxtBtn" @click="copyText('keyText', fourData, '签名为空，请稍后重试或联系管理员')">复制</span>
                      <span class="action aniTxtBtn" @click="downText('keyText', fourData, '未提供签名，请稍后重试或联系管理员', 'signature.json', 'application/json')">下载</span>
                    </div>
                  </div>
                  <div class="data-table data-table-scroll">
                    <p class="text-container">
                      {{ changeJSON(fourData.keyText) }}
                    </p>
                  </div>
                </div>
              </transition>
            </el-form>
          </div>

          <div class="task-container" v-else="selectApp === 4">
            <el-form ref="fiveForm" :model="fiveData" :rules="rules">
              <div class="data-show">
                <!-- 标题 -->
                <div class="data-actions data-title-between">
                  <h3>消息嵌入</h3> 
                </div>
                <!-- 内容区 -->
                <div class="data-table">
                  <!-- 通用布局行 -->
                  <div class="common-row">
                    <div class="common-item item-5">
                      <label class="condition-label">参数选择</label>
                      <el-form-item class="condition-input" prop="parameter">
                        <el-select v-model="fiveData.parameter" clearable placeholder="请选择参数文件">
                          <el-option v-for="(item, index) in parameters" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                      </el-form-item>
                    </div>
                    <div class="common-item item-5">
                      <label class="condition-label">媒体类型</label>
                      <el-form-item class="condition-input" prop="module">
                        <el-select @change="moduleChange" v-model="fiveData.module" clearable placeholder="请选择类型">
                          <el-option v-for="(item, index) in modules" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                      </el-form-item>
                    </div>
                  </div>
                  <!-- 通用布局行 -->
                  <div class="common-row">
                    <div class="common-item item-10" :class="{'item-upload': uploadObj.promptFilePath.showFileList}">
                      <el-tooltip content="切换上传方式" placement="top">
                        <label class="condition-label condition-label-change" @click="changeUploadType('promptFilePath', 'promptFilePath', fiveData)">提示词</label>
                      </el-tooltip>
                      <el-form-item class="condition-input" prop="promptFilePath">
                        <el-upload
                          v-if="uploadObj.promptFilePath.isUploadType"
                          class="upload"
                          :ref="uploadObj.uploadRef('promptFilePath')"
                          drag
                          :action="uploadObj.uploadUrl"
                          :limit="1"
                          :show-file-list="uploadObj.promptFilePath.showFileList"
                          :before-upload="uploadObj.beforeUpload('promptFilePath', 'promptFilePath')"
                          :on-success="uploadObj.onSuccess('promptFilePath', 'promptFilePath', fiveData,fiveForm)"
                          :on-progress="uploadObj.onProgress('promptFilePath')"
                          :on-error="uploadObj.onError('promptFilePath')"
                          :on-remove="uploadObj.onRemove('promptFilePath')"
                        >
                          <transition name="upload">
                            <div class="upload-empty" v-if="!fiveData.promptFilePath">
                              <i class="iconfont icon-icon_update upload-icon"></i>
                              <p class="upload-des">拖拽文件至此或点击上传</p>
                            </div>
                            <div class="upload-content" v-else>
                              <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                              <p class="upload-des">{{ uploadObj.promptFilePath.fileName }}</p>
                            </div>
                          </transition>
                        </el-upload>
                        <el-input v-else type="textarea" @input="clearData('promptFilePath', fiveData)" @change="createBlobTxt($event, 'promptFilePath', 'promptFilePath', fiveData, fiveForm)" v-model="uploadObj.promptFilePath.text" show-word-limit :rows="5" resize="none" placeholder="请输入文本" />
                      </el-form-item>
                    </div>
                  </div>
                  <!-- 通用布局行 - 任务密钥 -->
                  <div class="common-row">
                    <div class="common-item item-10" :class="{'item-upload': uploadObj.keyFilePath.showFileList}">
                      <el-tooltip content="切换上传方式" placement="top">
                        <label class="condition-label condition-label-change" @click="changeUploadType('keyFilePath', 'keyFilePath', fiveData)">协商密钥</label>
                      </el-tooltip>
                      <el-form-item class="condition-input" prop="keyFilePath">
                        <el-upload
                          class="upload"
                          v-if="uploadObj.keyFilePath.isUploadType"
                          :ref="uploadObj.uploadRef('keyFilePath')"
                          drag
                          :action="uploadObj.uploadUrl"
                          :limit="1"
                          :show-file-list="uploadObj.keyFilePath.showFileList"
                          :before-upload="uploadObj.beforeUpload('keyFilePath', 'keyFilePath')"
                          :on-success="uploadObj.onSuccess('keyFilePath', 'keyFilePath', fiveData, fiveForm)"
                          :on-progress="uploadObj.onProgress('keyFilePath')"
                          :on-error="uploadObj.onError('keyFilePath')"
                          :on-remove="uploadObj.onRemove('keyFilePath')"
                        >
                          <transition name="upload">
                            <div class="upload-empty" v-if="!fiveData.keyFilePath">
                              <i class="iconfont icon-icon_update upload-icon"></i>
                              <p class="upload-des">拖拽文件至此或点击上传</p>
                            </div>
                            <div class="upload-content" v-else>
                              <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                              <p class="upload-des">{{ uploadObj.keyFilePath.fileName }}</p>
                            </div>
                          </transition>
                        </el-upload>
                        <el-input v-else type="textarea" @input="clearData('keyFilePath', fiveData)" @change="createBlobTxt($event, 'keyFilePath', 'keyFilePath', fiveData, fiveForm)" v-model="uploadObj.keyFilePath.text" show-word-limit :rows="5" resize="none" placeholder="请输入文本" />
                      </el-form-item>
                    </div>
                  </div>
                  <!-- 通用布局行 - message -->
                  <div class="common-row">
                    <div class="common-item item-10" :class="{'item-upload': uploadObj.messageFilePath.showFileList}">
                      <label class="condition-label">消息文件</label>
                      <el-form-item class="condition-input" prop="messageFilePath">
                        <el-upload
                          class="upload"
                          :ref="uploadObj.uploadRef('messageFilePath')"
                          drag
                          :action="uploadObj.uploadUrl"
                          :limit="1"
                          :show-file-list="uploadObj.messageFilePath.showFileList"
                          :before-upload="uploadObj.beforeUpload('messageFilePath', 'messageFilePath')"
                          :on-success="uploadObj.onSuccess('messageFilePath', 'messageFilePath', fiveData, fiveForm)"
                          :on-progress="uploadObj.onProgress('messageFilePath')"
                          :on-error="uploadObj.onError('messageFilePath')"
                          :on-remove="uploadObj.onRemove('messageFilePath')"
                        >
                        <transition name="upload">
                          <div class="upload-empty" v-if="!fiveData.messageFilePath">
                            <i class="iconfont icon-icon_update upload-icon"></i>
                            <p class="upload-des">拖拽文件至此或点击上传</p>
                          </div>
                          <div class="upload-content" v-else>
                            <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                            <p class="upload-des">{{ uploadObj.messageFilePath.fileName }}</p>
                          </div>
                        </transition>
                        </el-upload>
                      </el-form-item>
                    </div>
                  </div>
                </div>
              </div>
              <transition name="upload">
                <!-- 按钮部分 -->
                <div class="btn-groups" v-if="!fiveData.embeddingFilePath">
                  <button type="button" class="btn btn-normal" @click="handleCancel">取消</button>
                  <button :disabled="fiveData.btnFlag" type="button" class="btn" @click="handleFive">隐写</button>
                </div>
                <div class="data-show" v-else>
                  <!-- 标题 -->
                  <div class="data-actions data-title-between">
                    <h3>载密文件</h3>
                    <div class="data-title-actions">
                      <span class="action aniTxtBtn" @click="downloadFile">下载</span>
                    </div>
                  </div>
                  <div class="data-table data-table-scroll">
                    <el-image class="file-image" v-if="fiveData.module === '图像'" :src="fiveData.stego" fit="contain" :preview-src-list="[fiveData.stego]" />
                    <p v-else-if="fiveData.module === '文本'" class="text-container">
                      {{ fiveData.stego }}
                    </p>
                    <div class="audio-container audio-show" v-else>
                      <i class="iconfont icon-swticonyinle audio-icon"></i>
                      <p class="audio-filename">{{ fiveData.stego }}</p>
                      <!-- <audio class="audio" :src="fiveData.stego" controls></audio> -->
                    </div>
                  </div>
                </div>
              </transition>
            </el-form>
          </div>
        </transition>
      </el-col>
    </el-row>
  </div>
</template>
<script setup>
import useAppStore from '@/stores/app';
import { ref, computed, onActivated } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { API } from '@/utils/status.js';
import { ElMessage } from 'element-plus';
import * as uploadApi from '@/api/file';
import * as rule from '@/utils/rules';
import * as request from '@/api/steganography';

const parameters = API.steCommon.parameters;
const modules = API.steCommon.modules;
const keyTypes = API.publicSteg.keyTypes;
const apps = [
  { value: 0, label: '服务器公钥解密' },
  { value: 1, label: '生成协商密钥参数' },
  { value: 2, label: '生成协商密钥' },
  { value: 3, label: '生成签名' },
  { value: 4, label: '消息嵌入' }
];

const defaultOne = {
  btnFlag: false,
  userId: null,
  keyType: null,
  keyTextFilePath: null,
  key: null
}
const defaultTwo = {
  btnFlag: false,
  userId: null,
  keyType: null,
  keyText: null
};
const defaultThree = {
  btnFlag: false,
  userId: null,
  keyType: null,
  keyTextFilePath: null,
  key: null
}
const defaultFour = {
  btnFlag: false,
  userId: null,
  keyType: null,
  keyText: null
};
const defaultFive = {
  promptFilePath: null,
  keyFilePath: null,
  messageFilePath: null,
  module: null,
  parameter: null,
  embeddingFilePath: null,
  stego: null
};
const defaultUpload = {
  isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
}

// ============> data <============
const appStore = useAppStore();
const route = useRoute();
const router = useRouter();
const selectApp = ref(0);
const oneForm = ref(null);
const twoForm = ref(null);
const threeForm = ref(null);
const fourForm = ref(null);
const fiveForm = ref(null);

const oneData = ref({
  btnFlag: false,
  userId: null,
  keyType: null,
  keyTextFilePath: null,
  key: null
});
const twoData = ref({
  btnFlag: false,
  userId: null,
  keyType: null,
  keyText: null
});
const threeData = ref({
  btnFlag: false,
  userId: null,
  keyType: null,
  keyTextFilePath: null,
  key: null
});
const fourData = ref({
  btnFlag: false,
  userId: null,
  keyType: null,
  keyText: null
});
const fiveData = ref({
  promptFilePath: null,
  keyFilePath: null,
  messageFilePath: null,
  module: null,
  parameter: null,
  embeddingFilePath: null,
  stego: null
});


// 上传控制对象
const uploadObj = ref({
  uploadUrl: `${import.meta.env.VITE_FILE_BASE_API}${uploadApi.uploadUrl}`,
  uploadRef(key){
    return function (dom){
      if (dom){
        uploadObj.value[key].dom = dom;
      }
    }
  },
  beforeUpload(uploadKey, dataKey){
    return function (file){
      if (uploadObj.value[uploadKey].uploading){
        ElMessage.warning('当前有文件正在上传，请稍后重试');
        return false;
      }
      let extension = file.size < API.upload.commonLimit;
      if (!extension) {
        ElMessage.warning(`上传文件超过大小限制，文件须小于${API.upload.commonLimit / (1024 * 1024)}M`)
      }
      let fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
      if (dataKey === 'keyTextFilePath'){
        extension = fileType == 'json' ? true : false;
        if (!extension){
          ElMessage.warning('上传文件须为json文件!');
        }
      }
      if (dataKey === 'promptFilePath' || (dataKey === 'messageFilePath' && fiveData.value.module == '文本')){
        extension = fileType == 'txt' ? true : false;
        if (!extension){
          ElMessage.warning('上传文件须为txt文件!');
        }
      }
      if (dataKey === 'keyFilePath'){
        extension = fileType == 'txt' ? true : false;
        if (!extension){
          ElMessage.warning('上传文件须为txt文件!');
        }
      }
      uploadObj.value[uploadKey].fileName = extension ? file.name : '';
      uploadObj.value[uploadKey].showFileList = true;
      return extension;
    }
  },
  onSuccess(uploadKey, dataKey, data, form){
    return function (e){
      uploadObj.value[uploadKey].dom.clearFiles();
      uploadObj.value[uploadKey].showFileList = false;
      uploadObj.value[uploadKey].uploading = false;
      console.log('上传res')
      console.log(e)
      if (e.code === API.code.SUCCESS) { 
        ElMessage.success('上传成功');
        data[dataKey] = e.data.path;
      } else {
        let msg = e.msg || e.message || '上传失败，请稍后重试或联系管理员';
        ElMessage({
          type: 'error',
          duration: 1500,
          message: msg
        });
      }
      form.validateField([dataKey])
    }
  },
  onProgress(key){
    return function (e){
      uploadObj.value[key].showFileList = true;
      uploadObj.value[key].uploading = true;
    }
  },
  onError(key){
    return function (e){
      console.log(e)
      let message = e.msg || e.message || '上传失败，请稍后重试或联系管理员'
      ElMessage({
        type: 'error',
        duration: 1500,
        message
      });
      uploadObj.value[key].showFileList = false;
      uploadObj.value[key].uploading = false;
      uploadObj.value[key].dom.clearFiles();
      uploadObj.value[key].fileName = '';
    }
  },
  onRemove(key){
    return function (e){
      uploadObj.value[key].showFileList = false;
      uploadObj.value[key].uploading = false;
      uploadObj.value[key].dom.clearFiles();
      uploadObj.value[key].fileName = '';
    }
  },
  oneKeyTextFilePath: {
    isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  },
  threeKeyTextFilePath: {
    isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  },
  keyFilePath: {
    isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  },
  promptFilePath: {
    isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  },
  messageFilePath: {
    isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  }
});
// 表单验证规则
const rules = {
  userId: rule.createRequired('发布用户不能为空'),
  keyType: rule.createRequired('算法模块不能为空'),
  // keyTextFilePath: rule.createRequired('请上传公钥密文'),
  keyTextFilePath: rule.createTextUpload(uploadObj.value, 'oneKeyTextFilePath', '公钥密文不能为空'),
  module: rule.createRequired('请选择任务类型'),
  // promptFilePath: rule.createRequired('请上传提示词'),
  promptFilePath: rule.createTextUpload(uploadObj.value, 'promptFilePath', '提示词不能为空'),
  // keyFilePath: rule.createRequired('请上传协商密钥'),
  keyFilePath: rule.createTextUpload(uploadObj.value, 'keyFilePath', '协商密钥不能为空'),
  messageFilePath: rule.createRequired('请上传消息文件'),
  parameter: rule.createRequired('参数文件不能为空')
};
const threeRules = {
  userId: rule.createRequired('发布用户不能为空'),
  keyType: rule.createRequired('算法模块不能为空'),
  // keyTextFilePath: rule.createRequired('请上传公钥密文'),
  keyTextFilePath: rule.createTextUpload(uploadObj.value, 'threeKeyTextFilePath', '公钥密文不能为空'),
  module: rule.createRequired('请选择任务类型'),
  promptFilePath: rule.createRequired('请上传提示词'),
  keyFilePath: rule.createRequired('请上传协商密钥'),
  messageFilePath: rule.createRequired('请上传消息文件')
};
const changeJSON = computed(() => {
  return function (jsonString){
    return jsonString ? window.decodeURIComponent(JSON.parse(jsonString)) : '';
  }
})


// ============> hookes <============
onActivated(() => {
  init()
});

// ============> method <============
function init(){
  oneData.value = Object.assign({}, defaultOne);
  twoData.value = Object.assign({}, defaultTwo);
  threeData.value = Object.assign({}, defaultThree);
  fourData.value = Object.assign({}, defaultFour);
  fiveData.value = Object.assign({}, defaultFive);
  uploadObj.value.oneKeyTextFilePath = Object.assign({}, defaultUpload);
  uploadObj.value.threeKeyTextFilePath = Object.assign({}, defaultUpload);
  uploadObj.value.keyFilePath = Object.assign({}, defaultUpload);
  uploadObj.value.promptFilePath = Object.assign({}, defaultUpload);
  uploadObj.value.messageFilePath = Object.assign({}, defaultUpload);
}
function changeUploadType(uploadKey, dataKey, data){
  uploadObj.value[uploadKey].isUploadType = !uploadObj.value[uploadKey].isUploadType;
  uploadObj.value[uploadKey].text = '';
  uploadObj.value[uploadKey].showFileList = false;
  uploadObj.value[uploadKey].fileName = '';
  uploadObj.value[uploadKey].uploading = false;
  data[dataKey] = null;
}
function clearData(key, data){
  data[key] = '';
}
// 输入文本上传
function createBlobTxt(e, uploadKey, dataKey, data, form){
  if (!e){
    data[dataKey] = null;
    ElMessage.success('上传成功');
    return;
  }
  let fileType, filename;
  switch (uploadKey){
    case 'keyFilePath':
      // filename = 'keyText.json';
      // fileType = 'application/json';
      filename = 'key.txt';
      fileType = 'text/plain';
      // filename = 'keyFile.yaml';
      // fileType = 'text/yaml';
      break;
    case 'signatureFilePath':
      filename = 'signature.json';
      fileType = 'application/json';
      break;
    case 'promptFilePath':
      filename = 'prompt.txt';
      fileType = 'text/plain';
      break;
    default:
      filename = 'keyTextFile.json';
      fileType = 'application/json';
      break;
  }
  const blob = new Blob([e], { type: fileType});
  const file = new File([blob], filename, { type: fileType});
  let formData = new FormData();
  formData.append('file', file);
  uploadApi.upload(formData)
    .then(res => {
      console.log(res);
      ElMessage.success('上传成功');
      data[dataKey] = res.path;
      uploadObj.value[uploadKey].fileName = filename;
      form.validateField([dataKey])
    })
    .catch(err => {
      console.log(err);
      let msg = err.msg || err.message || '上传失败，请稍后重试或联系管理员';
      ElMessage.error(msg);
      form.validateField([dataKey])
    })
}
// 通用复制
function copyText(key, data, warning = '内容为空，请稍后重试或联系管理员'){
  if (!data[key]) {
    ElMessage.warning(warning);
    return;
  }
  if (navigation.clipboard){
    navigation.clipboard.writeText(data[key])
      .then(res => {
        ElMessage.success('已复制到剪切板');
      })
      .catch(err => {
        ElMessage.error('复制失败');
      })
  } else if (document.execCommand){
    const textarea = document.createElement('textarea');
    textarea.value = data[key];
    document.body.appendChild(textarea);
    textarea.select();
    try {
      const successful = document.execCommand('copy');
      if (successful){
        ElMessage.success('已复制到剪切板');
      } else {
        ElMessage.error('复制失败');
      }
    } catch(err){
      console.log('sss')
      ElMessage.error(err);
    }
    document.body.removeChild(textarea); 
  }
}
// 通用下载
function downText(key, data, warning = '下载内容为空，请稍后再试或联系管理员', filename='keyText.json', type='application/json'){
  if (!data[key]){
    ElMessage.warning(warning);
    return;
  }
  const blob = new Blob([data[key]], { type });
  const link = document.createElement('a');
  const fileUrl = window.URL.createObjectURL(blob);
  link.href = fileUrl;
  link.download = filename;
  ElMessage.success('下载开始');
  link.click();
  window.URL.revokeObjectURL(fileUrl);
}
// 载体下载
function downloadFile(){
  uploadApi.download({filePath: fiveData.value.embeddingFilePath})
    .then(res => {
      let fileUrl = window.URL.createObjectURL(res.data),
          a = document.createElement('a');
          // disposition = res.headers['content-disposition'],
          // filename = disposition.slice(disposition.lastIndexOf('=') + 1);
      let origin = fiveData.value.embeddingFilePath,
          index;
      if (origin.lastIndexOf('\\') > 0){
        index = origin.lastIndexOf('\\');
      } else if (origin.lastIndexOf('/') > 0){
        index = origin.lastIndexOf('/');
      }
      let filename = origin.slice(index + 1);
      a.href = fileUrl;
      a.download = filename;
      a.click();
      ElMessage.success('下载开始！');
      window.URL.revokeObjectURL(fileUrl);
    })
    .catch(err => {
      let message = err.msg || err.message || err.data.msg || '下载失败，请稍后重试或联系管理员';
      ElMessage.error(message);
    })
}
function moduleChange(e){
  fiveData.value.messageFilePath = null;
  uploadObj.value.messageFilePath.fileName = null;
  uploadObj.value.messageFilePath.isUploadType = true;
  uploadObj.value.messageFilePath.text = '';
  uploadObj.value.messageFilePath.showFileList = false;
  uploadObj.value.messageFilePath.fileName = '';
  uploadObj.value.messageFilePath.uploading = false;
  if (uploadObj.value.messageFilePath.dom) uploadObj.value.messageFilePath.dom.clearFiles();
}
function selectAppChange(){
  init()
}
function handleCancel(){
  router.back();
}
function handleOne(){
  if (oneData.value.btnFlag){
    ElMessage.warning('当前正在进行,请稍后');
    return;
  }
  oneForm.value.validate(valid => {
    if (valid){
      oneData.value.btnFlag = true;
      appStore.openLoading('解密中...');
      request.appThreeClientExtractPublishKey({
        userId: oneData.value.userId,
        keyTextFilePath: oneData.value.keyTextFilePath,
        keyType: oneData.value.keyType
      })
        .then(res => {
          oneData.value.btnFlag = false;
          appStore.closeLoading();
          if (res && res.key){
            ElMessage.success('解密成功');
            oneData.value.key = res.key;
          } else {
            ElMessage.error('解密失败，请稍后重试或联系管理员');
          }
        })
        .catch(err => {
          console.log(err);
          oneData.value.btnFlag = false;
          appStore.closeLoading();
        })
    } else {
      ElMessage.warning('提交信息有误，请核对后提交');
    }
  })
}
function handleTwo(){
  if (twoData.value.btnFlag){
    ElMessage.warning('当前正在进行,请稍后');
    return;
  }
  twoForm.value.validate(valid => {
    if (valid){
      twoData.value.btnFlag = true;
      appStore.openLoading('生成中...');
      request.appThreeClientEmbeddingPublishKey({
        userId: twoData.value.userId,
        keyType: twoData.value.keyType
      })
        .then(res => {
          console.log(res);
          twoData.value.btnFlag = false;
          appStore.closeLoading();
          if (res && res.keyText) {
            ElMessage.success('生成成功');
            twoData.value.keyText = res.keyText;
          } else {
            ElMessage.error('生成失败，请稍后重试或联系管理员');
          }
        })
        .catch(err => {
          console.log(err);
          twoData.value.btnFlag = false;
          appStore.closeLoading();
        })
    } else {
      ElMessage.warning('提交信息有误，请核对后提交');
    }
  })
}
function handleThree(){
  if (threeData.value.btnFlag){
    ElMessage.warning('当前正在进行,请稍后');
    return;
  }
  threeForm.value.validate(valid => {
    if (valid){
      threeData.value.btnFlag = true;
      appStore.openLoading('生成中...');
      request.appThreeClientSharedKey({
        userId: threeData.value.userId,
        keyType: threeData.value.keyType,
        keyTextFilePath: threeData.value.keyTextFilePath
      })
        .then(res => {
          threeData.value.btnFlag = false;
          appStore.closeLoading();
          if (res && res.key){
            ElMessage.success('生成成功');
            threeData.value.key = res.key;
          } else {
            ElMessage.error('生成失败，请稍后重试或联系管理员');
          }
        })
        .catch(err => {
          console.log(err);
          threeData.value.btnFlag = false;
          appStore.closeLoading();
        })
    } else {
      ElMessage.warning('提交信息有误，请核对后提交');
    }
  })
}
function handleFour(){
  if (fourData.value.btnFlag){
    ElMessage.warning('当前正在进行,请稍后');
    return;
  }
  fourForm.value.validate(valid => {
    if (valid){
      fourData.value.btnFlag = true;
      appStore.openLoading('签名生成中...');
      request.appThreeClientSign({
        userId: fourData.value.userId,
        keyType: fourData.value.keyType
      })
        .then(res => {
          fourData.value.btnFlag = false;
          appStore.closeLoading();
          if (res && res.keyText){
            ElMessage.success('签名生成成功');
            fourData.value.keyText = res.keyText;
          } else {
            ElMessage.error('签名生成失败，请稍后重试或联系管理员');
          }
        })
        .catch(err => {
          console.log(err);
          appStore.closeLoading();
          fourData.value.btnFlag = false;
        })
    } else {
      ElMessage.warning('提交信息有误，请核对后提交');
    }
  })
}
function handleFive(){
  if (fiveData.value.btnFlag){
    ElMessage.warning('当前正在进行,请稍后');
    return;
  }
  fiveForm.value.validate(valid => {
    if (valid){
      fiveData.value.btnFlag = true;
      appStore.openLoading('消息嵌入中...');
      request.appThreeClientMessage({
        module: fiveData.value.module,
        parameter: fiveData.value.parameter,
        promptFilePath: fiveData.value.promptFilePath,
        keyFilePath: fiveData.value.keyFilePath,
        messageFilePath: fiveData.value.messageFilePath,
      })
        .then(res => {
          console.log(res)
          fiveData.value.btnFlag = false;
          appStore.closeLoading();
          if (res && res.embeddingFilePath){
            ElMessage.success('消息嵌入成功');
            fiveData.value.embeddingFilePath =  res.embeddingFilePath;
            uploadApi.download({filePath: res.embeddingFilePath})
              .then(result => {
                console.log(result)
                if (fiveData.value.module === '图像') {
                  fiveData.value.stego = window.URL.createObjectURL(result.data);
                } else if (fiveData.value.module === '文本') {
                  let reader = new FileReader();
                  console.log(reader)
                  reader.readAsText(result.data, 'UTF-8');
                  reader.onload= function(evt){
                    fiveData.value.stego = evt.target.result || ''
                  }
                } else {
                  console.log(result.headers)
                  // let disposition = result.headers['content-disposition'],
                  //     filename = disposition.slice(disposition.lastIndexOf('=') + 1);
                  let origin = res.embeddingFilePath,
                      index;
                  if (origin.lastIndexOf('\\') > 0){
                    index = origin.lastIndexOf('\\');
                  } else if (origin.lastIndexOf('/') > 0){
                    index = origin.lastIndexOf('/');
                  }
                  let filename = origin.slice(index + 1);
                  fiveData.value.stego = filename;
                }
              })
          } else {
            ElMessage.error('消息嵌入失败，请稍后重试或联系管理员');
          }
        })
        .catch(err => {
          console.log(err);
          fiveData.value.btnFlag = false;
          appStore.closeLoading();
        })
    } else {
      ElMessage.warning('提交信息有误，请核对后提交');
    }
  })
}
</script>
<style lang='scss' scoped>
@import '@/assets/styles/mixin.scss';
.row-between {
  justify-content: space-between;
}
.item-3 {
  width: 30%
}
.item-5 {
  width: 49%;
}
.item-10 {
  width: 100%;
  height: auto;
  padding: 20px 0;
  .condition-label {
    width: 15%;
  }
  .condition-input {
    width: 80%;
  }
}
.upload {
  width: 100%;
  min-height: 120px;
  height: 120px;
  &::v-deep .el-upload {
    @include wh-100;
    // height: 100%!important;
    .el-upload-dragger {
      @include wh-100;
      border-color: var(--color-main);
      padding: 0;
      .upload-empty {
        @include wh-100;
        @include flex-all-center;
        flex-direction: column;
        .upload-icon {
          font-size: 30px;
          color: var(--color-gray-10);
        }
        .upload-des {
          color: var(--color-gray-10);
        }
      }
      .upload-content {
        @include wh-100;
        @include flex-all-center;
        flex-direction: column;
        .upload-icon {
          font-size: 30px;
          color: var(--color-main);
        }
        .upload-des {
          color: var(--color-main);
        }
      }
    }
  }
}
.btn-groups {
  margin-top: 20px;
  text-align: center;
  .btn {
    margin: 0 20px;
  }
}
.apps_container {
  @include flex-all-center;
  text-align: center;
  flex-direction: column;
  & .el-radio {
    display: block;
    margin: 0;
    line-height: 32px;
    margin: 10px 0;
    width: 100%;
    background-color: var(--color-gray-5);
    border-radius: 4px;
    color: var(--color-main);
    transition: all 0.3s;
  }
  & .el-radio.is-checked {
    background: var(--color-main);
  }
  & .el-radio::v-deep .el-radio__label {
    transition: all 0.3s;
  }
  & .el-radio.is-checked::v-deep .el-radio__label {
    color: var(--color-white-10)!important;
  }
  & .el-radio::v-deep .el-radio__input{
    display: none;
  }
}
.item-upload {
  padding-bottom: 50px;
}
.data-table-scroll {
  max-height: 220px;
  height: auto;
  overflow-y: auto;
  @include scrollBar;
  .file-image {
    width: 100%;
    height: 190px;
    background-color: var(--color-gray-2);
    border: 1px solid var(--color-main-border);
    border-radius: 6px;
  }
}
.data-title-between {
  @include flex-between-center;
  .data-title-actions {
    @include flex-all-center;
    height: 40px;
    padding: 4px 8px;
    border-radius: 8px;
  }
}
.condition-label-change {
  cursor: pointer;
}
.condition-label-change:hover {
  color: var(--color-primary);
}
.audio-container {
  width: 100%;
  height: 190px;
  background-color: var(--color-gray-2);
  border: 1px solid var(--color-main-border);
  border-radius: 6px;
  position: relative;
  overflow: hidden;
  @include flex-all-center;
  .audio-icon {
    font-size: 40px;
    font-weight: bolder;
    color: var(--color-main);
  }
  .audio {
    position: absolute;
    bottom: 0;
    left: 50%;
    width: 105%;
    height: 30px;
    transform: translateX(-50%);
  }
}
.audio-show {
  @include flex-all-center;
  flex-direction: column;
}
.audio-show > .audio-filename {
  margin-top: 10px;
  color: var(--color-main);
}
</style>